//
// Created by ct on 2020/10/10.
//

#include "request_handler.h"

#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include "mime_types.h"
#include "request.h"
#include "reply.h"

namespace http{
    namespace server {
        request_handler::request_handler(std::string  doc_root):doc_root_(std::move(doc_root)) {}

        void request_handler::handle_request(const request &req, reply &rep) {
//            std::cout<<"method: "<<req.method<<std::endl;
//            std::cout<<"uri: "<<req.uri<<std::endl;
//            std::cout<<"http_version_major: "<<req.http_version_major<<std::endl;
//            std::cout<<"http_version_minor: "<<req.http_version_minor<<std::endl;
//            for(const auto& h : req.headers){
//                std::cout<<h.name<<": "<<h.value<<std::endl;
//            }
            // 解码url到路径。
            std::string request_path;
            if (!request_handler::url_decode(req.uri,request_path)){
                rep = reply::stock_reply(reply::bad_request);
                return;
            }
 //           std::cout<<"request_path: "<<request_path<<std::endl;
            // 如果路径以斜杠结尾（即，是一个目录），则添加“索引.html".
//            if (request_path[request_path.size() - 1] == '/')
//            {
//                request_path += "index.html";
//            }
//            // 确定文件扩展名。
//            std::size_t last_slash_pos = request_path.find_last_of("/");
//            std::size_t last_dot_pos = request_path.find_last_of(".");
            std::string extension = "json";
//            if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos)
//            {
//                extension = request_path.substr(last_dot_pos + 1);
//            }
//            std::cout<<"extension: "<<extension<<std::endl;
            // 返回打开文件。
//            std::string full_path = doc_root_ + request_path;
//            std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
//            if (!is)
//            {
//                rep = reply::stock_reply(reply::not_found);
//                return;
//            }
            // 填写要发送给客户的回复。

//
//            char buf[512];
//            while (is.read(buf, sizeof(buf)).gcount() > 0)
//                rep.content.append(buf, is.gcount());
//
            rep.content.append(R"({"number-of-nodes":"8","flow":"5 kb/s"})");
            // 添加头信息
            rep.status = reply::ok;
            rep.headers.resize(2);
            rep.headers[0].name = "Content-Length";
            rep.headers[0].value = std::to_string(rep.content.size());
            rep.headers[1].name = "Content-Type";
            rep.headers[1].value = mime_types::extension_to_type(extension);
        }

        bool request_handler::url_decode(const std::string &in, std::string &out) {
            out.clear();
            out.reserve(in.size());

            for (std::size_t i = 0; i < in.size(); ++i)
            {
                if (in[i] == '%')
                {
                    if (i + 3 <= in.size())
                    {
                        int value = 0;
                        std::istringstream is(in.substr(i + 1, 2));
                        if (is >> std::hex >> value)
                        {
                            out += static_cast<char>(value);
                            i += 2;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (in[i] == '+')
                {
                    out += ' ';
                }
                else
                {
                    out += in[i];
                }
            }
            return true;
        }
    } // namespace server

} // namespace http